<template>
    <van-sticky z-index="100">
        <van-nav-bar
            title="我的收货地址"
            left-text="返回"
            left-arrow
            @click-left="onBack"
        />
    </van-sticky>

        <!-- 从订单结算 -->
    <van-address-list
        v-model="AddressId"
        :list="list"
        default-tag-text="默认"
        @add="toAdd"
        @edit="toEdit"
        @select="onSelected"
        v-if="action === 'order'"
    />

    <van-address-list
        v-model="selectedAddressId"
        :list="list"
        default-tag-text="默认"
        @add="toAdd"
        @edit="toEdit"
        @select="onSelect"
        v-else
    />

</template>
<script setup>
import { getCurrentInstance, reactive, ref, onMounted } from 'vue';

// 定义变量
const { proxy } = getCurrentInstance();
const list = ref([]);
const selectedAddressId = ref(0);
const business = reactive(proxy.$cookies.get('business') ? proxy.$cookies.get('business') : {});
const action = ref(proxy.$route.query.action ? proxy.$route.query.action : '');
const AddressId = ref(proxy.$cookies.get('address') ? proxy.$cookies.get('address').id : selectedAddressId);

onMounted(() => {
    getData();
})

const getData = async () => {
    let data = {
        busid:business.id
    }

    let result = await proxy.$api.getAddressData(data);

    if(result.code === 0)
    {
        proxy.$showNotify({
            type:'warning',
            message:result.msg,
            duration:1500
        });

        return;
    }

    let addressList = [];

    for(let item of result.data)
    {
        addressList.push({
            id:item.id,
            name:item.consignee,
            tel:item.mobile,
            address:item.region_text + ' ' + item.address,
            isDefault:item.status == 1 ? true : false
        });

        if(item.status == 1)
        {
            selectedAddressId.value = item.id;
        }
    }

    list.value = addressList;
}

const onSelect = async (info) => {
    let data = {
        id:info.id,
        busid:business.id
    }

    let result = await proxy.$api.AddressSelected(data);

    if(result.code === 1)
    {
        getData();
    }else{
        proxy.$showNotify({
            type:'warning',
            message:result.msg,
            duration:1500
        });

        return;
    }

}

const onSelected = (info) => {

    let data = {
        id:info.id,
        mobile:info.tel,
        consignee:info.name
    }

    proxy.$cookies.set('address',data);

    proxy.$router.back();
}

// 去新增收货地址
const toAdd = () => {
    proxy.$router.push('/business/address/add');
    return;
}

// 去编辑收货地址
const toEdit = (info) => {
    proxy.$router.push({path:'/business/address/edit',query:{id:info.id}});
    return;
}

// 定义返回事件
const onBack = () => {
    proxy.$router.go(-1);
}
</script>